package mygang.dao.manager;

import java.util.List;
import mygang.model.constructor.field.Field;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 */
@Repository("fieldDAO")
@Transactional
public class FieldDAOImpl extends AbstractManageDAO<Field> implements FieldDAO {
    private static final Logger log = Logger.getLogger(AbstractManageDAO.class.toString());
    
    @Autowired
    private TableDAO tableDAO;

    public void saveValue(Field field) {
        try{
            Field data = getById(field.getId());
            log.debug(data);
            
            // prepares parameters
            Query query = getSession().createSQLQuery(prepareQuery(data, true));
            query.setParameter("VALUE", field.getValue());
            query.setParameter("ID", + field.getEntityId());

            int result = query.executeUpdate();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }

    public void fillValue(Field field) {
        try{
            Field data = getById(field.getId());
            log.debug(data);
            
            // prepares parameters
            Query query = getSession().createSQLQuery(prepareQuery(data, false));
            query.setParameter("ID", + field.getEntityId());
            
            List result = query.list();
            log.debug(result);
            if(!result.isEmpty()){
                String value = result.get(0).toString();
                log.debug("value = "+value);
                field.setValue(value);
            }
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private String prepareQuery(Field data, boolean isUpdate){
            String tableName = data.getEntity().getTable().getName();
            StringBuilder sb = new StringBuilder();
            if(isUpdate){
                sb.append("UPDATE " + tableName+ " ");
                sb.append("SET " + data.getColumnName() + " = :VALUE ");
            } else {
                sb.append("SELECT " + data.getColumnName() + " FROM "+tableName+ " ");
            }
            sb.append("WHERE " + tableDAO.getTablePrimaryColumn(tableName) + " = :ID");
            log.debug("QUERY: "+sb.toString());
            return sb.toString();
    }
}
